import React from 'react';
import { Card, Form, Table, Modal } from 'antd';
import { get as getPath } from 'object-path';
import { Pagination } from '@/components';
import { connect } from 'umi';
import moment from 'moment';
import { formatMessage } from 'umi';
import cn from 'classnames';
import LinkTo from '@/components/LinkTo';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import DataPick2 from '@/components/DatePicker2';
import { dateConversion2 } from '@/utils/utils';
import { withRoutePage } from '@/utils/enhanceUtils';
import styles from '../Holiday.less';

class OverList extends React.Component {
    state = {
        orderByField: '',
        dateOption: [
            {
                en: 'year',
                cn: '今年'
            },
            {
                en: 'month',
                cn: '本月'
            },
            {
                en: 'week',
                cn: '本周'
            }
        ],
        times: [
            moment(
                moment()
                    .month(moment().month())
                    .startOf('month')
                    .format('YYYY-MM-DD')
            ),
            moment()
        ],
        visible: false,
        signDate: '',
        columnsModal: [
            {
                title: '工号',
                dataIndex: 'userNo',
                key: 'userNo'
            },
            {
                title: '打卡时间',
                dataIndex: 'attDatetime',
                key: 'attDatetime'
            },
            {
                title: '考勤来源',
                dataIndex: 'deviceName',
                key: 'deviceName'
            }
        ],
        overStatus: [],
        overSign: [],
        columns: [],
        filter: {},
        sorters: ''
    };

    componentDidMount() {
        const { times } = this.state;
        this.getTypeListAll();
        if (getPath(this.props, 'location.query.date')) {
            const date = [
                moment(
                    moment(getPath(this.props, 'location.query.date'))
                        .startOf('month')
                        .format('YYYY-MM-DD')
                ),
                moment(
                    moment(getPath(this.props, 'location.query.date'))
                        .endOf('month')
                        .format('YYYY-MM-DD')
                )
            ];
            this.handleSearch(date);
        } else {
            this.handleSearch(times);
        }
    }

    componentWillUnmount() {
        const {
            dispatch,
            overtimeList: { pagination }
        } = this.props;

        dispatch({
            type: 'overtimeList/setPagination',
            pagination: {
                ...pagination,
                pageSize: 10,
                current: 1
            }
        });
    }

    handleSearch = (v, type) => {
        this.setState(
            {
                times: v
            },
            () => {
                this.fetchList(getPath(type, ''));
            }
        );
    };

    // 获取列表
    fetchList = type => {
        const { times } = this.state;
        const {
            dispatch,
            overtimeList: { pagination }
        } = this.props;
        const parame = {
            startTime: times[0].format('YYYY-MM-DD'),
            endTime: times[1].format('YYYY-MM-DD'),
            pageNo: type ? 1 : pagination.current,
            pageSize: pagination.pageSize,
            orderByField: getPath(this.state, 'orderByField', ''),
            overStatus: getPath(this.state, 'overStatus', []),
            overSign: getPath(this.state, 'overSign', [])
        };
        dispatch({
            type: 'overtimeList/fetchMyovertim',
            payload: parame
        });
    };

    showModal = () => {
        this.setState({
            visible: true
        });
    };

    setVisible = type => {
        this.setState({
            visible: type
        });
    };

    // 打卡记录
    seeDetail = record => {
        const { dispatch } = this.props;
        const user = JSON.parse(localStorage.getItem('user'));
        const parame = {
            employeeCode: getPath(user, 'employeeCode', ''),
            startTime: moment(record.applyStartTime).format('YYYY-MM-DD'),
            endTime: moment(record.applyEndTime).format('YYYY-MM-DD'),
            pageNo: 1,
            pageSize: 10
        };
        dispatch({
            type: 'overtimeList/fetchMydetail',
            payload: parame
        }).then(() => {
            this.setState({
                signDate: moment(record.overDate).format('YYYY-MM-DD')
            });
            this.showModal();
        });
    };

    // 表格表头点击切换排序
    changeTable = async (pagination, filters, sorter) => {
        const { sorters, filter } = this.state;
        let orderBy;
        let sorterField;
        if (sorter && sorter.field && sorter.order) {
            if (sorter.field === 'applyStartTime') {
                sorterField = 'apply_start_time';
            }
            if (sorter.field === 'startTime') {
                sorterField = 'start_time';
            }
            if (sorter.field === 'overLong') {
                sorterField = 'over_long';
            }
            const order = sorter.order.trim().split('end')[0];
            orderBy = `${sorterField} ${order}`;
            this.setState({
                orderByField: orderBy
            });
        } else {
            this.setState({
                orderByField: ''
            });
        }
        const { dispatch, overtimeList } = this.props;
        await dispatch({
            type: 'overtimeList/setPagination',
            pagination: {
                ...overtimeList.pagination,
                ...pagination
            }
        });
        // 新的分页组件无法自动回到第一页的bug修复
        if (filters && JSON.stringify(filter) !== JSON.stringify(filters)) {
            this.setState({
                filter: filters
            });
            await dispatch({
                type: 'overtimeList/setPagination',
                pagination: {
                    ...overtimeList.pagination,
                    current: 1
                }
            });
        }
        if (sorter && sorters !== sorter) {
            this.setState({
                sorters: sorter
            });
            await dispatch({
                type: 'overtimeList/setPagination',
                pagination: {
                    ...overtimeList.pagination,
                    current: 1
                }
            });
        }
        this.setState(
            {
                overSign: filters && filters.overtimeSignNick,
                overStatus: filters && filters.statusNick
            },
            () => {
                this.fetchList();
            }
        );
    };

    // 获取类型字典
    getTypeListAll = () => {
        const { dispatch } = this.props;
        const param = {
            dictCode: 'overtimeStatus'
        };
        const param2 = {
            dictCode: 'overtimeSign'
        };
        dispatch({
            type: 'overtimeList/fetchTypeList',
            payload: param,
            callback: () => {
                dispatch({
                    type: 'overtimeList/fetchOverType',
                    payload: param2,
                    callback: () => {
                        this.setfilters();
                    }
                });
            }
        });
    };

    // 加班类型/是否加班 调整column
    setfilters = () => {
        const {
            overtimeList: { typeList, overType }
        } = this.props;
        const dictColor = {
            0: '#52C41A',
            1: 'rgba(0,0,0,0.65)',
            2: '#F5222D'
        };
        const column = [
            {
                title: `${formatMessage({
                    id: 'stat.over.overtimeSignNick'
                })}`,
                dataIndex: 'overtimeSignNick',
                key: 'overtimeSignNick',
                filters: []
            },
            {
                title: `${formatMessage({
                    id: 'stat.over.applyStartTime'
                })}`,
                dataIndex: 'applyStartTime',
                key: 'applyStartTime',
                render: (text, record) => (
                    <div>
                        <p>{record.applyStartTime}</p>
                        <p>{record.applyEndTime}</p>
                    </div>
                ),
                sorter: () => {}
            },
            {
                title: `${formatMessage({
                    id: 'stat.over.statusNick'
                })}`,
                dataIndex: 'statusNick',
                key: 'statusNick',
                filters: [],
                render(text, record) {
                    return <span style={{ color: dictColor[record.status] }}>{record.statusNick}</span>;
                }
            },
            {
                title: `${formatMessage({
                    id: 'stat.over.startTime'
                })}`,
                dataIndex: 'startTime',
                key: 'startTime',
                render: (text, record) => (
                    <div>
                        {record.status && record.status === 1 ? (
                            <div>
                                <p>{record.startTime}</p>
                                <p>{record.endTime}</p>
                            </div>
                        ) : (
                            <span>--</span>
                        )}
                    </div>
                ),
                sorter: () => {}
            },
            {
                title: `${formatMessage({
                    id: 'stat.over.overLong'
                })}`,
                dataIndex: 'overLong',
                key: 'overLong',
                render: (text, record) => (
                    <div>
                        {record.status && record.status === 1 ? (
                            <span>{dateConversion2(record.overLong)}</span>
                        ) : (
                            <span>--</span>
                        )}
                    </div>
                ),
                sorter: () => {}
            },
            {
                title: `${formatMessage({
                    id: 'stat.miss.applicationNo'
                })}`,
                dataIndex: 'applicationNo',
                key: 'applicationNo',
                width: 200,
                render: (text, record) => {
                    const { remark = '', applicationNo } = record;
                    const flag = remark === 'hide';
                    const isOldFlow = !applicationNo.includes('-');
                    const url = isOldFlow
                        ? '/personal/portal/flow/mine/myApplication/detail'
                        : '/personal/portal/myApplication/detail';
                    const params = { applicationNo };

                    return (
                        <span>
                            {text === '' ? (
                                '--'
                            ) : (
                                <LinkTo to={url} query={params} className={cn({ [styles.disabled]: flag })}>
                                    {text}
                                </LinkTo>
                            )}
                        </span>
                    );
                }
            },
            {
                title: `${formatMessage({
                    id: 'stat.absence.action'
                })}`,
                dataIndex: 'action',
                key: 'action',
                render: (text, record) => (
                    <div>
                        {record.status && record.status !== 0 ? (
                            <a onClick={() => this.seeDetail(record)}>
                                {formatMessage({
                                    id: 'stat.absence.seeDetail'
                                })}
                            </a>
                        ) : (
                            <span>--</span>
                        )}
                    </div>
                )
            }
        ];

        const overStatus = [];
        const overSign = [];
        for (let index = 0; index < typeList.length; index += 1) {
            const list = {
                text: typeList[index].dictName,
                value: typeList[index].dictValue
            };
            overStatus.push(list);
        }

        for (let i = 0; i < overType.length; i += 1) {
            const list = {
                text: overType[i].dictName,
                value: overType[i].dictValue
            };
            overSign.push(list);
        }
        column[0].filters = overSign;
        column[2].filters = overStatus;
        this.setState({
            columns: column
        });
    };

    render() {
        const { loading, overtimeList } = this.props;
        const { overtimeData, pagination, attenddetail } = overtimeList;
        const { dateOption, signDate, columnsModal, visible, columns } = this.state;
        let defaultDate;
        if (getPath(this.props, 'location.query.date') && getPath(this.props, 'location.query.date') !== 'undefined') {
            defaultDate = getPath(this.props, 'location.query.date');
        }
        return (
            <PageHeaderWrapper>
                <Card
                    title={formatMessage({
                        id: 'stat.over.title'
                    })}
                    bordered={false}
                    className={styles.card}
                    extra={
                        <DataPick2
                            onSearch={v => {
                                this.handleSearch(v, 'over', true);
                            }}
                            dateOption={dateOption}
                            mode="month"
                            defaultDate={defaultDate}
                        />
                    }
                >
                    <Table
                        bordered={false}
                        dataSource={overtimeData}
                        columns={columns}
                        loading={loading}
                        rowKey="id"
                        onChange={this.changeTable}
                        pagination={false}
                    />
                    <Pagination {...pagination} onChange={this.changeTable} loading={loading} />
                    {/* <Table
                        dataSource={overtimeData}
                        columns={columns}
                        loading={loading}
                        rowKey="id"
                        onChange={this.changeTable}
                        pagination={{
                            ...pagination,
                            itemRender,
                            showTotal: total => (
                                <TablePagination
                                    itemsName={Locale.set('items')}
                                    total={total}
                                    pageSize={pagination.pageSize}
                                    onChange={async pageSize => {
                                        await dispatch({
                                            type: 'overtimeList/setPagination',
                                            pagination: {
                                                ...pagination,
                                                pageSize,
                                                current: 1
                                            }
                                        });
                                        this.fetchList();
                                    }}
                                />
                            )
                        }}
                    /> */}
                    <Modal
                        title={
                            <div>
                                <div style={{ fontSize: '20px', color: '#333' }}>
                                    {formatMessage({
                                        id: 'stat.ckdkjl'
                                    })}
                                </div>
                                <p
                                    style={{
                                        color: 'rgba(0, 0, 0, .45)',
                                        fontSize: '14px',
                                        marginBottom: 0
                                    }}
                                >
                                    {signDate}
                                    {formatMessage({
                                        id: 'stat.dksj'
                                    })}
                                </p>
                            </div>
                        }
                        width={600}
                        footer={null}
                        visible={visible}
                        onOk={() => this.setVisible(false)}
                        onCancel={() => this.setVisible(false)}
                        centered
                    >
                        <Table
                            dataSource={attenddetail}
                            columns={columnsModal}
                            pagination={false}
                            loading={loading}
                            rowKey="id"
                        />
                    </Modal>
                </Card>
            </PageHeaderWrapper>
        );
    }
}

export default withRoutePage(
    connect(({ overtimeList, loading }) => ({
        overtimeList,
        loading: loading.models.overtimeList
    }))(Form.create()(OverList))
);
